package top.buaarobot.webserver.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonSerializer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.buaarobot.webserver.config.PathParams;
import top.buaarobot.webserver.domain.*;
import top.buaarobot.webserver.repository.*;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/tutorial")
public class TutorialResource {

    private String docPath = PathParams.BasePath + PathParams.DocDir;
    private final MarkdownFileRepository markdownFileRepository;

    public TutorialResource(MarkdownFileRepository markdownFileRepository) {
        this.markdownFileRepository = markdownFileRepository;
    }



    @PostMapping(value = "/upload/markdownfile")
    public ResponseEntity<String> addMarkdownFile(@RequestBody JSONObject json){
        MarkdownFile markdownFile = new MarkdownFile();
        markdownFile.setAuthor(json.getString("author"));
        markdownFile.setDate(json.getString("date"));
        markdownFile.setEmail(json.getString("email"));
        markdownFile.setParentid(Integer.parseInt(json.getString("parentid")));
        markdownFile.setCatalog(json.getString("catalog"));
        markdownFile.setFilename(json.getString("filename"));
        markdownFile.setText(json.getString("text"));

        this.markdownFileRepository.save(markdownFile);
        return ResponseEntity.ok().build();
    }

    @GetMapping(value = "/markdownfile/{id}")
    public ResponseEntity<MarkdownFile> getMarkdownFile(@PathVariable("id") Integer  id) throws FileNotFoundException {
        Optional<MarkdownFile> optionalMarkdownFile = this.markdownFileRepository.findById(id);
        if(optionalMarkdownFile.isPresent()){
            return ResponseEntity.ok().body(optionalMarkdownFile.get());
        }
        return ResponseEntity.badRequest().build();
    }

    @PostMapping(value = "/markdown/new")
    public ResponseEntity<Integer> generateNewMarkdownFile(@RequestBody JSONObject json){
        System.out.println(json);
        MarkdownFile md = new MarkdownFile();
        md.setFilename(json.getString("filename"));
        md.setAuthor(json.getString("author"));
        md.setDate(json.getString("date"));
        MarkdownFile res = this.markdownFileRepository.save(md);
        return ResponseEntity.ok().body(res.getId());
    }

    @PostMapping(value = "/markdown/delete")
    public ResponseEntity<String> deteleMarkdownFiles(@RequestBody JSONObject json){
        System.out.println("buenos test enter:");
        System.out.println(json.get("fileIds"));
        Iterable<Integer> fileIds = (Iterable<Integer>) json.get("fileIds");
        Iterable<MarkdownFile> markdownFiles = this.markdownFileRepository.findAllById(fileIds);
        this.markdownFileRepository.deleteAll(markdownFiles);
        return ResponseEntity.ok().body(null);
    }

    @PostMapping(value = "/markdown/update")
    public void updateMarkdownFile(@RequestBody JSONObject json){
        System.out.println("buenos test update json : " + json.toString());
        Integer id = Integer.parseInt(json.getString("id"));
        Optional<MarkdownFile> mdOptional = this.markdownFileRepository.findById(id);
        if(mdOptional.isPresent()){
            MarkdownFile md = mdOptional.get();
            md.setAuthor(json.getString("author"));
            md.setCatalog(json.getString("catalog"));
            md.setDate(json.getString("date"));
            md.setEmail(json.getString("email"));
            md.setFilename(json.getString("filename"));
            md.setText(json.getString("text"));
            this.markdownFileRepository.save(md);
        }
    }


    @GetMapping(value = "/markdownfileInfos/{catalog}")
    public ResponseEntity<JSONArray> getMarkdownFileInfos(@PathVariable("catalog") String  catalog) throws FileNotFoundException {
        Iterable<MarkdownFile> markdownFiles = this.markdownFileRepository.findAll();
        JSONArray jsonArray = new JSONArray();
        for(MarkdownFile mdfile: markdownFiles){
            if(mdfile.getCatalog() != null && mdfile.getCatalog().indexOf(catalog) != -1){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",mdfile.getId());
                jsonObject.put("author", mdfile.getAuthor());
                jsonObject.put("title", mdfile.getFilename());
                jsonArray.add(jsonObject);
            }
        }
        return ResponseEntity.ok().body(jsonArray);
    }





    @GetMapping(value = "/download/file/{filename}")
    public ResponseEntity<FileSystemResource> downloadFile(@PathVariable("filename") String fileName) throws FileNotFoundException {
        File file = new File(docPath, fileName);
        if (file.exists()) {
            return export(file);
        }
        return null;
    }


    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "inline; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
    }

}
